<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" :request-api="getTableList" :init-param="initParam">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button v-if="BUTTONS.add" type="primary" :icon="CirclePlus" @click="openDrawer('新增')"> 新增 </el-button>
        <el-button v-if="BUTTONS.import" type="primary" :icon="Upload" plain @click="batchAdd">导入数据</el-button>
        <el-button v-if="BUTTONS.export" type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" v-if="BUTTONS.edit" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" v-if="BUTTONS.delete" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <ItemDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, computed } from "vue";
import { ExportObj, Item } from "@/api/types/base";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import ItemDrawer from "./itemDrawer.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View, Download, Upload } from "@element-plus/icons-vue";
import apiService from "@/api/services/apiService";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { dateRender, enumRender, orgRender, productRender, userRender, yearRender } from "@/hooks/useColumnRender";
import { useDataStore } from "@/stores/modules/data";
import { onMounted } from "vue";
import { useDownload } from "@/hooks/useDownload";
import { ElMessageBox } from "element-plus";
// import { useDateFormat } from "@vueuse/core";
import { ExportColType } from "@/enums/sysEnum";
import { useDateFormat } from "@vueuse/core";

const dataStore = useDataStore();
const { BUTTONS } = useAuthButtons();
// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

const initVar = reactive({
  tbName: "item"
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  // let newParams = JSON.parse(JSON.stringify(params));
  return apiService.findPage(initVar.tbName, params.condition, params.options);
};

const productList = computed(() => dataStore.productList);
const orgList = computed(() => dataStore.orgList);
const customerList = computed(() => dataStore.getEnumByCsName("customer_classify"));
const userList = computed(() => dataStore.userList);
onMounted(() => {
  dataStore.findProductList();
  dataStore.findOrgList();
  dataStore.findEnumByCsName("customer_classify");
  dataStore.findUserList();
});

// 表格配置项
const columns = reactive<ColumnProps<Item>[]>([
  { type: "index", label: "序号", width: 65 },
  {
    prop: "base",
    label: "基本信息",
    _children: [
      { prop: "item_no", label: "项目编号", search: { el: "input", like: true }, width: 120 },
      { prop: "name", align: "left", label: "项目名称", search: { el: "input", like: true }, width: 200 },
      { prop: "year", label: "年度", render: yearRender },
      {
        prop: "start_date",
        label: "立项时间",
        width: 120,
        render: dateRender
      },
      { prop: "customer", label: "客户", width: 140, render: scope => enumRender(scope, customerList) },
      {
        prop: "level",
        label: "项目级别",
        width: 90,
        // 字典请求携带参数
        enum: () => apiService.findClassify("ITEM_LEVEL"),
        search: { el: "select", props: { filterable: true } },
        fieldNames: { label: "name", value: "value" }
      },
      { prop: "main_product", label: "主产品", width: 90, render: scope => productRender(scope, productList) }
      // { prop: "support_product", label: "辅产品", width: 140 }
    ]
  },
  {
    prop: "stakeholder",
    label: "干系人",
    _children: [
      { prop: "dev_org_id", label: "主研发组", width: 140, render: scope => orgRender(scope, orgList) },
      { prop: "release_org_id", label: "交付负责组", width: 140, render: scope => orgRender(scope, orgList) },
      { prop: "relase_charge_user", label: "交付负责人", width: 100, render: scope => userRender(scope, userList) },
      { prop: "pre_sale_user", label: "售前负责人", width: 100, render: scope => userRender(scope, userList) }
    ]
  },
  {
    prop: "release",
    label: "交付情况",
    _children: [
      { prop: "plan_completion_date", label: "预计交付时间", width: 140, render: dateRender },
      { prop: "completion_date", label: "实际交付时间", width: 140, render: dateRender },
      {
        prop: "state",
        label: "项目状态",
        width: 100,
        // 字典请求携带参数
        enum: () => apiService.findClassify("ITEM_STATE"),
        search: { el: "select", props: { filterable: true } },
        fieldNames: { label: "name", value: "value" }
      }
    ]
  },
  { prop: "operation", label: "操作", fixed: "right", width: 220 }
]);

const getExcelConfig = (): ExportObj => {
  return {
    params: proTable.value?.searchParam,
    tableName: initVar.tbName,
    keyPropName: "item_no",
    enumTypes: ["ITEM_LEVEL", "ITEM_CLASSIFY", "customer_classify", "ITEM_STATE"],
    tableConfigs: [
      { tableName: "users", fields: ["_id", "userName"] },
      { tableName: "orgs", fields: ["_id", "name"] },
      { tableName: "product", fields: ["_id", "name"] }
    ],
    header: [
      { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
      { header: "项目编号", width: 15, ext: { prop: "item_no", type: ExportColType.DEFAULT } },
      { header: "项目年度", width: 10, ext: { prop: "year", type: ExportColType.DATE_YEAR } },
      { header: "项目名称", width: 40, ext: { prop: "name", type: ExportColType.DEFAULT } },
      { header: "立项时间", width: 10, ext: { prop: "start_date", type: ExportColType.DATE } },
      { header: "项目级别", width: 8, ext: { prop: "level", type: ExportColType.ENUM, key: "ITEM_LEVEL" } },
      {
        header: "项目类别",
        width: 10,
        ext: { prop: "classify", type: ExportColType.ENUM, key: "ITEM_CLASSIFY", label: "name", value: "_id" }
      },
      {
        header: "客户",
        width: 10,
        ext: { prop: "customer", type: ExportColType.ENUM, key: "customer_classify", label: "name", value: "_id" }
      },
      { header: "主产品", width: 10, ext: { prop: "main_product", type: ExportColType.TABLE, key: "product" } },
      { header: "辅产品", width: 10, ext: { prop: "support_product", mutil: true, type: ExportColType.TABLE, key: "product" } },
      { header: "项目简介", width: 30, ext: { prop: "summary", type: ExportColType.DEFAULT } },
      { header: "预计交付时间", width: 12, ext: { prop: "plan_completion_date", type: ExportColType.DATE } },
      { header: "实际交付时间", width: 12, ext: { prop: "completion_date", type: ExportColType.DATE } },
      { header: "项目状态", width: 10, ext: { prop: "state", type: ExportColType.ENUM, key: "ITEM_STATE" } },
      { header: "研发产品组", width: 18, ext: { prop: "dev_org_id", type: ExportColType.TABLE, key: "orgs" } },
      { header: "交付负责组", width: 18, ext: { prop: "release_org_id", type: ExportColType.TABLE, key: "orgs" } },
      {
        header: "交付负责人",
        width: 10,
        ext: { prop: "relase_charge_user", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      {
        header: "售前负责人",
        width: 10,
        ext: { prop: "pre_sale_user", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      {
        header: "创建人",
        width: 10,
        ext: { prop: "create_user", type: ExportColType.TABLE, key: "users", label: "userName", value: "_id" }
      },
      { header: "创建时间", width: 12, ext: { prop: "create_at", type: ExportColType.DATE } }
    ]
  };
};

// 导出数据
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(apiService.commonExport, `项目清单-${useDateFormat(new Date(), "YYYY-MM-DD").value}`, "", getExcelConfig(), false)
  );
};

// 导入数据
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: "项目",
    defaultTip: "项目编号相同则跳过",
    coverTip: "项目编号相同则覆盖",
    tempUrl: "/template/item",
    getTableList: proTable.value?.getTableList,
    importApi: apiService.commonImport,
    config: getExcelConfig()
  };
  dialogRef.value?.acceptParams(params);
};

// 删除用户信息
const deleteAccount = async (params: Item) => {
  await useHandleData(apiService.deleteById, initVar.tbName, params._id, `删除项目【${params.name}】`);
  proTable.value?.getTableList();
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof ItemDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Item> = {}) => {
  const params = {
    title,
    tbName: initVar.tbName,
    isView: title === "查看",
    row: { ...row },
    api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};
</script>
